package com.chromatic.competition.service;

import com.chromatic.competition.view.notifications.ChatActivity;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Socket;

public class MessageReceiver implements Runnable {
    private final Socket socket;
    private BufferedReader input;

    /**
     * 构造函数，初始化 MessageReceiver 对象
     *
     * @param socket        Socket 对象，用于接收消息
     * @param chatActivity  ChatActivity 对象，用于更新 UI
     */
    public MessageReceiver(Socket socket, ChatActivity chatActivity) {
        this.socket = socket;
        try {
            this.input = new BufferedReader(new InputStreamReader(this.socket.getInputStream()));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void run() {
        try {
            String message;
            while ((message = input.readLine()) != null) {
                // 在接收到消息时，通过 ChatActivity 的回调方法更新 UI
//                chatActivity.onMessageReceived(message);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                input.close();
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}